package com.wcl.demo.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.wcl.demo.R;
import com.wcl.demo.ui.activity.AddFriendActivity;
import com.wcl.demo.ui.activity.ChatActivity;
import com.wcl.demo.ui.fragment.ItemInterface.FriendOnItemListener;
import com.wcl.demo.utils.ActivityUtils;
import com.wcl.demo.view.CustomDialog;
import com.wcl.demo.view.CustomToast;
import com.wcl.demo.view.sortlistview.CharacterParser;
import com.wcl.demo.view.sortlistview.ClearEditText;
import com.wcl.demo.view.sortlistview.GroupMemberBean;
import com.wcl.demo.view.sortlistview.PinyinComparator;
import com.wcl.demo.view.sortlistview.SideBar;
import com.wcl.demo.view.sortlistview.SortGroupMemberAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * Created by dllo on 15/12/8.
 */
public class FriendsFragment extends Fragment implements View.OnClickListener {
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortGroupMemberAdapter adapter;
    private ClearEditText mClearEditText;
    private int lastFirstVisibleItem = -1;
    private CharacterParser characterParser;
    private List<GroupMemberBean> SourceDateList;
    private PinyinComparator pinyinComparator;
    private RelativeLayout fragment_friend_addItem;

    private LinearLayout titleLayout;
    private TextView title;
    private TextView tvNofriends;
    private List<String> usernames;
    private AddFriBC addFriBC;
    private Context context;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.lanou.addFriend");
        addFriBC = new AddFriBC();
        context.registerReceiver(addFriBC, intentFilter);//注册广播

        View view = inflater.inflate(R.layout.activity_add_friends, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        titleLayout = (LinearLayout) view.findViewById(R.id.title_layout);
        title = (TextView) view.findViewById(R.id.title_layout_catalog);
        tvNofriends = (TextView) view.findViewById(R.id.title_layout_no_friends);
        sideBar = (SideBar) view.findViewById(R.id.sidrbar);
        dialog = (TextView) view.findViewById(R.id.dialog);
        sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
        mClearEditText = (ClearEditText) view.findViewById(R.id.filter_edit);
        fragment_friend_addItem = (RelativeLayout) view.findViewById(R.id.fragment_friend_addItem);
        fragment_friend_addItem.setOnClickListener(this);

    }

    private String[] friends;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        EMChatManager.getInstance().getChatOptions().setUseRoster(true);
        try {
            usernames = EMChatManager.getInstance().getContactUserNames();
            friends = new String[usernames.size()];
            for (int i = 0; i < usernames.size(); i++) {
                friends[i] = usernames.get(i);
            }
            Log.i("jhhjdsjkk", usernames.size() + "" + usernames);
        } catch (EaseMobException e) {
            e.printStackTrace();
        }
        if (usernames.size() > 0) {
            initView();
            initData();
            listener();
        }
    }

    private void initView() {
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        SourceDateList = filledData(friends);
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortGroupMemberAdapter(getActivity(), SourceDateList);

    }

    private void initData() {

        sideBar.setTextView(dialog);
        sortListView.setAdapter(adapter);
        sortListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {
                int section = getSectionForPosition(firstVisibleItem);
                int nextSection;
                if (friends.length > 1) {
                    nextSection = getSectionForPosition(firstVisibleItem + 1);
                }else {
                    nextSection = getSectionForPosition(firstVisibleItem);
                }
                int nextSecPosition = getPositionForSection(+nextSection);
                if (firstVisibleItem != lastFirstVisibleItem) {
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                            .getLayoutParams();
                    params.topMargin = 0;
                    titleLayout.setLayoutParams(params);
                    title.setText(SourceDateList.get(
                            getPositionForSection(section)).getSortLetters());
                }
                if (nextSecPosition == firstVisibleItem + 1) {
                    View childView = view.getChildAt(0);
                    if (childView != null) {
                        int titleHeight = titleLayout.getHeight();
                        int bottom = childView.getBottom();
                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
                                .getLayoutParams();
                        if (bottom < titleHeight) {
                            float pushedDistance = bottom - titleHeight;
                            params.topMargin = (int) pushedDistance;
                            titleLayout.setLayoutParams(params);
                        } else {
                            if (params.topMargin != 0) {
                                params.topMargin = 0;
                                titleLayout.setLayoutParams(params);
                            }
                        }
                    }
                }
                lastFirstVisibleItem = firstVisibleItem;
            }
        });
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                // ���ʱ����Ҫ��ѹЧ�� �Ͱ������ص�
                titleLayout.setVisibility(View.GONE);
                // ������������ֵΪ�գ�����Ϊԭ�����б?����Ϊ��������б�
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

    private void listener() {
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            public void onTouchingLetterChanged(String s) {
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });
        adapter.setOnfriendOnItemLongListener(new FriendOnItemListener() {
            @Override
            public void setOnfriendOnItemListener(String username) {
                Bundle bundle = new Bundle();
                bundle.putString("username", username);
                ActivityUtils.startToActivity(getActivity(), ChatActivity.class, bundle);
            }

            @Override
            public void setOnfriendOnItemLongListener(final String username) {
                CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
                builder.setTitle("提示信息");
                builder.setMessage("确认要删除该好友吗?");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        try {
                            EMContactManager.getInstance().deleteContact(username);

                            usernames = EMChatManager.getInstance().getContactUserNames();
                            friends = new String[usernames.size()];
                            for (int i = 0; i < usernames.size(); i++) {
                                friends[i] = usernames.get(i);
                            }
                            SourceDateList = filledData(friends);
                            Collections.sort(SourceDateList, pinyinComparator);

                        } catch (EaseMobException e) {
                            e.printStackTrace();
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });

    }

    private List<GroupMemberBean> filledData(String[] date) {
        List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>();

        for (int i = 0; i < date.length; i++) {
            GroupMemberBean sortModel = new GroupMemberBean();
            sortModel.setName(date[i]);
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    private void filterData(String filterStr) {
        List<GroupMemberBean> filterDateList = new ArrayList<GroupMemberBean>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
            tvNofriends.setVisibility(View.GONE);
        } else {
            filterDateList.clear();
            for (GroupMemberBean sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(name).startsWith(
                        filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
        if (filterDateList.size() == 0) {
            tvNofriends.setVisibility(View.VISIBLE);
        }
    }

    public Object[] getSections() {
        return null;
    }

    public int getSectionForPosition(int position) {

        return SourceDateList.get(position).getSortLetters().charAt(0);

    }

    public int getPositionForSection(int section) {
        for (int i = 0; i < SourceDateList.size(); i++) {
            String sortStr = SourceDateList.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onClick(View v) {
        ActivityUtils.startToActivity(getActivity(), AddFriendActivity.class);
        // Intent intent = new Intent(getActivity(), AddFriendActivity.class);
    }

    class AddFriBC extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                usernames = EMChatManager.getInstance().getContactUserNames();

                if (usernames.size() > 0) {
                    friends = new String[usernames.size()];
                    for (int i = 0; i < usernames.size(); i++) {
                        friends[i] = usernames.get(i);
                    }
                    initView();
                    initData();
                    listener();
                }
//                SourceDateList = filledData(friends);
//                Collections.sort(SourceDateList, pinyinComparator);
            } catch (EaseMobException e) {
                e.printStackTrace();
            }
            Log.i("Sysout", "添加好友他");
        }
    }

    @Override
    public void onDestroy() {

        context.unregisterReceiver(addFriBC);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();

        try {
            usernames = EMChatManager.getInstance().getContactUserNames();

            if (usernames.size() > 0) {
                friends = new String[usernames.size()];
                for (int i = 0; i < usernames.size(); i++) {
                    friends[i] = usernames.get(i);
                }
                initView();
                initData();
                listener();
            }
//            SourceDateList = filledData(friends);
//            Collections.sort(SourceDateList, pinyinComparator);
        } catch (EaseMobException e) {
            e.printStackTrace();
        }
    }
}

